package com.ruoyi.back.service.impl

import cn.hutool.core.date.DateUnit
import cn.hutool.core.date.DateUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.ruoyi.back.domain.UserMember
import com.ruoyi.back.enums.UserTypeEnum
import com.ruoyi.back.mapper.UserMemberMapper
import com.ruoyi.back.service.UserMemberService
import org.springframework.stereotype.Service
import java.util.*

@Service
class UserMemberServiceImpl : ServiceImpl<UserMemberMapper, UserMember>(), UserMemberService {

    override fun getUserMemberByUserId(userId: Long): UserMember? =
        getOne(KtQueryWrapper(UserMember::class.java).eq(UserMember::createBy, userId))

    override fun addUserMember(beginDate: Date, expireData: Date, userId: Long) {

        getOne(KtQueryWrapper(UserMember::class.java).eq(UserMember::createBy, userId))
            ?.run {
                updateById(this.apply {
                    endMemberDate = expireData
                })
            }
            ?: kotlin.run {
                save(UserMember().apply {
                    createBy = userId
                    beginMemberDate = beginDate
                    endMemberDate = expireData
                })
            }
    }

    override fun removeUserMember(userId: Long): Boolean =
        remove(KtQueryWrapper(UserMember::class.java).eq(UserMember::createBy, userId))

    override fun userMemberType(userId: Long): UserTypeEnum =
        getOne(KtQueryWrapper(UserMember::class.java).eq(UserMember::createBy, userId))
            ?.run {
                if (DateUtil.between(
                        endMemberDate,
                        DateUtil.date(),
                        DateUnit.MS,
                        false
                    ) > 0
                ) UserTypeEnum.EXPIRE_MEMBER else UserTypeEnum.MEMBER
            } ?: UserTypeEnum.NORMAL


}